package com.haohan.cloud.scm.api.salec.trans;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.haohan.cloud.scm.api.constant.enums.opc.YesNoEnum;
import com.haohan.cloud.scm.api.goods.dto.GoodsInfoDTO;
import com.haohan.cloud.scm.api.goods.vo.GoodsVO;
import com.haohan.cloud.scm.api.manage.vo.PhotoVO;
import com.haohan.cloud.scm.api.salec.dto.StoreProductInfoDTO;
import com.haohan.cloud.scm.api.salec.entity.*;
import com.haohan.cloud.scm.api.salec.vo.ResultAttrVO;
import com.haohan.cloud.scm.api.salec.vo.ResultAttrValueVO;
import com.haohan.cloud.scm.api.salec.vo.ResultVO;
import lombok.experimental.UtilityClass;

import java.math.BigDecimal;
import java.time.Instant;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author cx
 * @date 2019/6/21
 */
@UtilityClass
public class StoreProductTrans {
    public StoreProduct GoodsToStoreProductTrans(GoodsInfoDTO dto) {
        StoreProduct p = new StoreProduct();
        BeanUtil.copyProperties(dto, p);
        Long time = System.currentTimeMillis();
        //设置默认状态，真实状态由c端控制
        p.setIsHot(Integer.parseInt(YesNoEnum.no.getType()));
        p.setIsBenefit(Integer.parseInt(YesNoEnum.no.getType()));
        p.setIsBest(Integer.parseInt(YesNoEnum.no.getType()));
        p.setIsNew(Integer.parseInt(YesNoEnum.no.getType()));
        p.setIsPostage(Integer.parseInt(YesNoEnum.yes.getType()));
        if (dto.getIsDel() == Integer.parseInt(YesNoEnum.yes.getType())) {
            p.setIsDel(Integer.parseInt(YesNoEnum.no.getType()));
        } else {
            p.setIsDel(Integer.parseInt(YesNoEnum.yes.getType()));
        }
        p.setMerUse(Integer.parseInt(YesNoEnum.no.getType()));
        p.setGiveIntegral(BigDecimal.ZERO);
        p.setIsSeckill(Integer.parseInt(YesNoEnum.no.getType()));
        p.setIsBargain(Integer.parseInt(YesNoEnum.no.getType()));
        //设置虚拟销量60-200之间随机数，随c端增长
        Random rand = new Random();
        p.setFicti(rand.nextInt((200) % (200 - 60 + 1) + 60));
        //设置虚拟浏览量200-500之间随机数，随c端浏览增长
        p.setBrowse(rand.nextInt(500) % (500 - 200 + 1) + 200);
        if (p.getFicti() >= 100) {
            p.setIsHot(Integer.parseInt(YesNoEnum.yes.getType()));
        } else {
            p.setIsNew(Integer.parseInt(YesNoEnum.yes.getType()));
        }
        //设置默认邮费10元
        p.setPostage(BigDecimal.TEN);
        //设置关键字为商品名
        p.setKeyword(dto.getStoreName());
        p.setAddTime(Integer.parseInt(time.toString().substring(0, 10)));
        return p;
    }

    /**
     * 暂时使用转换, 后续优化
     *
     * @param goods
     * @return
     */
    public GoodsInfoDTO goodsInfoTrans(GoodsVO goods) {
        GoodsInfoDTO dto = new GoodsInfoDTO();
        dto.setId(Integer.parseInt(goods.getGoodsId()));
        dto.setMerId(0);
        dto.setShopId(goods.getShopId());
        dto.setImage(goods.getThumbUrl());
        dto.setStoreName(goods.getGoodsName());
        if (goods.getSimpleDesc() == null) {
            dto.setStoreInfo(goods.getGoodsName());
        } else {
            dto.setStoreInfo(goods.getSimpleDesc());
        }
        dto.setCateId(goods.getCategoryId());
        dto.setPrice(goods.getMarketPrice());
        dto.setVipPrice(goods.getMarketPrice());
        dto.setOtPrice(goods.getVirtualPrice());
        dto.setUnitName(goods.getUnit());
        dto.setSort(Integer.parseInt(goods.getSort()));
        dto.setStock(goods.getStorage().intValue());
        dto.setCost(goods.getMarketPrice());
        if (goods.getDetailDesc() == null) {
            dto.setDescription(goods.getGoodsName());
        } else {
            dto.setDescription(goods.getDetailDesc());
        }
        dto.setIsDel(goods.getIsMarketable() == YesNoEnum.yes ? 1 : 0);
        // 品牌id 暂未处理
//        if (null != goods.getBrandId()) {
//            dto.setBrand(Integer.parseInt(goods.getBrandId()));
//        }
        // 轮播图
        dto.setSliderImage(JSONUtil.toJsonStr(goods.getPhotoList().stream()
                .map(PhotoVO::getPicUrl).collect(Collectors.toList())
        ));
        //查询商品规格名称列表
        dto.setGoodsModelTotals(goods.getModelTotalList());
        dto.setModelInfo(goods.getModelList());
        return dto;
    }

    /**
     * 修改时, 部分属性不更新
     *
     * @param productInfo
     */
    public void productInfoToModify(StoreProductInfoDTO productInfo) {
        productInfo.setStoreInfo(null);
        productInfo.setPostage(null);
        productInfo.setSort(null);
        productInfo.setSales(null);
        productInfo.setIsHot(null);
        productInfo.setIsBenefit(null);
        productInfo.setIsNew(null);
        productInfo.setAddTime(null);
        productInfo.setIsPostage(null);
        productInfo.setMerUse(null);
        productInfo.setGiveIntegral(null);
        productInfo.setIsSeckill(null);
        productInfo.setIsBargain(null);
        productInfo.setIsGood(null);
        productInfo.setIsSub(null);
        productInfo.setFicti(null);
        productInfo.setBrowse(null);
        productInfo.setCodePath(null);
        productInfo.setSoureLink(null);
        productInfo.setVideoLink(null);
        productInfo.setTempId(null);
        productInfo.setSpecType(null);
        productInfo.setActivity(null);
        productInfo.setType(null);
    }

    public StoreProductAttrResult copyAttrResult(StoreProductInfoDTO productInfo) {
        StoreProductAttrResult attrResult = new StoreProductAttrResult();
//        attrResult.setId(productInfo.getId());
        attrResult.setProductId(productInfo.getId());
        attrResult.setResult(productInfo.getResult());
        attrResult.setChangeTime(productInfo.getChangeTime());
        attrResult.setType(productInfo.getType());
        return attrResult;
    }


    public StoreProductDescription copyDescription(StoreProductInfoDTO productInfo) {
        StoreProductDescription description = new StoreProductDescription();
        description.setProductId(productInfo.getId());
        description.setDescription(productInfo.getDescription());
        description.setType(productInfo.getType());
        return description;
    }

    /**
     * 转换商品详情
     * result json串处理
     * 商品规格列表
     * 商品规格名称列表
     *
     * @param goods
     * @param productInfo
     */
    public void attrInfoTrans(GoodsVO goods, StoreProductInfoDTO productInfo) {
        int size = Math.max(8, goods.getModelList().size() * 4 / 3 + 1);
        // result json串处理
        ResultVO resultVO = new ResultVO();
        List<ResultAttrVO> attrList = new ArrayList<>(size);
        List<ResultAttrValueVO> valueList = new ArrayList<>(size);
        resultVO.setAttr(attrList);
        resultVO.setValue(valueList);
        // 商品规格名称列表
        productInfo.setAttrList(goods.getAttrMap().entrySet().stream().map(entry -> {
                    ResultAttrVO attrVO = new ResultAttrVO();
                    attrVO.setValue(entry.getKey());
                    attrVO.setDetail(entry.getValue());
                    attrVO.setAttrHidden(false);
                    attrList.add(attrVO);

                    StoreProductAttr attr = new StoreProductAttr();
                    attr.setProductId(productInfo.getId());
                    attr.setAttrName(entry.getKey());
                    attr.setAttrValues(CollUtil.join(entry.getValue(), StrUtil.COMMA));
                    // 类型只设置0
                    attr.setType(0);
                    return attr;
                }).collect(Collectors.toList())
        );
        // 总库存, 销量
        final Integer[] total = {0, 0};
        // 商品规格列表
        productInfo.setAttrValueList((goods.getModelList().stream().map(model -> {
                    ResultAttrValueVO valueVO = new ResultAttrValueVO();
                    valueVO.setPic(model.getModelUrl());
                    valueVO.setPrice(model.getModelPrice());
                    valueVO.setCost(model.getCostPrice());
                    valueVO.setOtPrice(model.getVirtualPrice());
                    valueVO.setStock(model.getModelStorage().intValue());
                    valueVO.setBarCode(model.getModelCode());
                    valueVO.setWeight(model.getWeight());
                    valueVO.setVolume(model.getVolume());
                    valueVO.setBrokerage(BigDecimal.ZERO);
                    valueVO.setBrokerageTwo(BigDecimal.ZERO);

                    String[] infoArray = model.getModelInfo().split(",");
                    Map<String, String> detailMap = new HashMap<>(size);
                    for (int i = 0, len = infoArray.length; i < len; i++) {
                        String[] array = infoArray[i].split(":");
                        if (i == 0) {
                            valueVO.setValue1(array[1]);
                        }
                        if (i == 1) {
                            valueVO.setValue2(array[1]);
                        }
                        detailMap.put(array[0], array[1]);
                    }
                    valueVO.setDetail(detailMap);
                    valueList.add(valueVO);

                    StoreProductAttrValue attrValue = new StoreProductAttrValue();
                    attrValue.setId(model.getModelId());
                    attrValue.setProductId(productInfo.getId());
                    // 规格名称 需是自然顺序排列
                    attrValue.setSuk(String.join(StrUtil.COMMA, detailMap.values()));
                    attrValue.setStock(valueVO.getStock());
                    total[0] = total[0] + valueVO.getStock();
                    attrValue.setSales(0);
                    total[1] = total[1] + attrValue.getSales();
                    attrValue.setPrice(model.getModelPrice());
                    attrValue.setImage(model.getModelUrl());
                    attrValue.setUnique(model.getModelId());
                    attrValue.setCost(null == model.getCostPrice() ? BigDecimal.ZERO : model.getCostPrice());
                    attrValue.setBarCode(model.getModelCode());
                    attrValue.setOtPrice(null == model.getVirtualPrice() ? model.getModelPrice() : model.getVirtualPrice());
                    attrValue.setWeight(model.getWeight());
                    attrValue.setVolume(model.getVolume());
                    attrValue.setBrokerage(BigDecimal.ZERO);
                    attrValue.setBrokerageTwo(BigDecimal.ZERO);
                    attrValue.setType(0);
                    attrValue.setQuota(0);
                    attrValue.setQuotaShow(0);
                    return attrValue;
                }).collect(Collectors.toList()))
        );
        productInfo.setStock(total[0]);
        productInfo.setSales(total[1]);
        productInfo.setResult(JSONUtil.toJsonStr(resultVO));
    }

    public List<StoreProductCate> copyProductCate(StoreProductInfoDTO productInfo) {
        int time = (int) Instant.now().getEpochSecond();
        return StrUtil.split(productInfo.getCateId(), StrUtil.C_COMMA).stream()
                .map(cateId -> {
                    StoreProductCate cate = new StoreProductCate();
                    cate.setProductId(productInfo.getId());
                    try {
                        cate.setCateId(Integer.parseInt(cateId));
                    } catch (Exception e) {
                        cate.setCateId(null);
                    }
                    cate.setAddTime(time);
                    return cate;
                }).filter(item -> null != item.getCateId()).collect(Collectors.toList());
    }
}
